﻿namespace Pibby.Core.IO
{
	using invrt;

	public class PortableMediaDevice
	{
		#region Constructors

		public PortableMediaDevice()
		{
		}

		public PortableMediaDevice(string volumeName)
		{
			this.VolumeName = volumeName;
		}

		#endregion

		#region Properties

		public bool Enabled
		{
			get;
			set;
		}

		public RemovableDriveStatus Connected
		{
			get;
			private set;
		}		

		public string DriveName
		{
			get;
			set;
		}

		public string FriendlyName
		{
			get;
			set;
		}

		public string VolumeName
		{
			get;
			set;
		}

		public string Folder
		{
			get;
			set;
		}

		public OrganizationOption Organization
		{
			get;
			set;
		}

		public string Path
		{
			get
			{
				string path = string.Empty;

				if (!string.IsNullOrEmpty(this.DriveName) && !string.IsNullOrEmpty(this.Folder))
				{
					path = System.IO.Path.Combine(this.DriveName, this.Folder);
				}

				return path;
			}
		}

		public EjectOption EjectOption
		{
			get;
			set;
		}

		public IDrive Drive
		{
			get
			{
				IDriveFactory factory = InversionOfController.Factory.CreateTypeOf<IDriveFactory>();

				return factory.GetDriveByName(this.DriveName);
			}
		}

		#endregion Properties

		#region Methods

		public void CheckConnected(RemovableDriveEventArgs e)
		{
			if (this.Enabled)
			{
				if ((e.Status == RemovableDriveStatus.Connected) 
					&& (e.VolumeName == this.VolumeName))
				{
					this.DriveName = e.DriveName;
					this.Connected = e.Status;
				}
				else if (e.Status == RemovableDriveStatus.Disconnected)
				{
					if (!string.IsNullOrEmpty(e.DriveName) && e.DriveName == this.DriveName)
					{
						this.Connected = e.Status;
					}
				}
			}
		}

		public bool IsConnected()
		{
			return this.Connected == RemovableDriveStatus.Connected;
		}

		public bool IsDisconnected()
		{
			return this.Connected == RemovableDriveStatus.Disconnected;
		}

		public bool CanBeEjected()
		{
			return this.Enabled && this.IsConnected();
		}

		public string SuggestPathUsing(string subfolder)
		{
			string folder = this.Path;

			if (this.Organization == OrganizationOption.Split)
			{
				folder = System.IO.Path.Combine(this.Path, subfolder);
			}

			return folder;
		}

		public void Eject()
		{
			IEjectDevices ejector = InversionOfController.Factory.CreateTypeOf<IEjectDevices>();

			ejector.Eject(this.DriveName);
		}

		#endregion Methods
	}
}
